package com.rajesh.messageservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.google.gson.GsonBuilder;
import com.rajesh.messageservice.bean.Action;
import com.rajesh.messageservice.bean.ActionType;
import com.rajesh.messageservice.helper.GlobalConfig;

import java.net.URI;
import java.util.HashMap;

public class MsgBroadcastReceiver extends BroadcastReceiver  {
    public static final String ClientRegister = "rajesh.action.CLIENT_REGISTER";
    public static final String StartProtector = "rajesh.action.START_PROTECTOR";
    private static final String BootCompleted = "android.intent.action.BOOT_COMPLETED";

    public static final String ServiceProtectorAction = "com.rajesh.action.START_PROTECTOR";

    public MsgBroadcastReceiver(){
        super();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        switch (intent.getAction()){
            case BootCompleted:{
                Intent svcIntent = new Intent(context, MsgSvc.class);
                context.startService(svcIntent);
                break;
            }
            case StartProtector:{
                Intent msgSvcIntent = new Intent(ServiceProtectorAction);
                context.startService(msgSvcIntent);
                break;
            }
            case ClientRegister:{
                this.registerPluginClient(context, intent);
            }
            default:{
                break;
            }
        }
    }

    private void registerPluginClient(Context context, Intent intent){
        try{
            Bundle bundle = intent.getExtras();
            Action action = new Action();
            action.setType(ActionType.Registe);
            HashMap<String, Object> hashMap = action.getArgs();
            hashMap.put("Uin", bundle.getString("Uin"));
            hashMap.put("NickName", bundle.getString("NickName"));
            hashMap.put("UserName", bundle.getString("UserName"));
            hashMap.put("BelongOrgnization", GlobalConfig.CompanyIdentity);

            String jsonMsg = new GsonBuilder().create().toJson(action);
            SocketClient socketClient = new SocketClient(context, URI.create(GlobalConfig.SocketServer));
            if(socketClient.connectBlocking()){
                socketClient.send(jsonMsg);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
